package chat.server;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import chat.user.Group;
import chat.user.Message;
import chat.user.Request;
import chat.user.RequestMessage;
import chat.user.User;

public class SocketWriter implements Runnable {

	// private Socket socket;
	// private c oos;
	private SocketProcessor socket_processor;
	private ObjectOutputStream oos;
	Object sync = new Object();

	public SocketWriter() throws IOException {

	}

	@Override
	public synchronized void run() {

		try {

			for (;;Thread.sleep(500)){          //used to improve performance
			
			//while (true) {

				synchronized (sync) {

					// Thread.sleep(500);

					while (SocketProcessor.getCountOutQueue() > 0) {

						/*
						 * Message m = SocketProcessor.getMessage();
						 * 
						 * Group g =
						 * GroupProcessor.getGroup(m.getUser().getRelatedGroup
						 * ());
						 * 
						 * HashMap<String, Socket> socket_list =
						 * g.getUserSocketList();
						 * 
						 * for (Map.Entry<String, Socket> entry:
						 * socket_list.entrySet()){
						 * 
						 * Socket socket = entry.getValue();
						 * 
						 * BufferedOutputStream out = new
						 * BufferedOutputStream(socket.getOutputStream());
						 * ObjectOutputStream oos = new ObjectOutputStream(out);
						 * 
						 * oos.writeObject(m); oos.flush();
						 * 
						 * }
						 */

						Request r = SocketProcessor.getMessage();
						Socket socket = GroupProcessor.getSocket(r.getUser());
						//clearSocket(r);

						BufferedOutputStream out = new BufferedOutputStream(
								socket.getOutputStream());
						ObjectOutputStream oos = new ObjectOutputStream(out);

						oos.writeObject(r);
						oos.flush();

						SocketProcessor.removeMessageOutQueue(r);
					}
				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
	
	private void clearSocket(Request r){
		
		r.removeSocket();
		
	}

	/*
	 * public void requestAuthentification(){
	 * 
	 * try {
	 * 
	 * Message m = new Message(); m.AUTH_REQUEST=true;
	 * 
	 * oos.writeObject(m); oos.flush(); } catch (IOException e){
	 * 
	 * e.printStackTrace(); } }
	 */
}
